<template>
    <section class="todoapp">
			<header class="header">
				<h1>todos</h1>
				<input class="new-todo" placeholder="What needs to be done?" autofocus v-model.trim="content" @keyup.enter="addData">
			</header>
			<!-- This section should be hidden by default and shown when there are todos -->
			<section class="main" v-show="todoList.length">
				<input id="toggle-all" class="toggle-all" type="checkbox" v-model="toggleAll">
				<label for="toggle-all">Mark all as complete</label>
				<ul class="todo-list">
					<!-- These are here just to show the structure of the list items -->
					<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
					<li :class="{'completed':item.completed,editing:current==item}" v-for="(item,index) in filterTodoList">
						<div class="view">
							<input class="toggle" type="checkbox" v-model="item.completed">
							<label @dblclick="editItem(item)">{{item.content}}</label>
							<button class="destroy" @click="removeItem(index)"></button>
						</div>
						<input class="edit" :value="current?.content"
						@keyup.esc="cancelEdit"
						@keyup.enter="$event.target.blur()"
						@blur="finishEdit(index,item,$event)"
						>
					</li>
					
				</ul>
			</section>
			<!-- This footer should be hidden by default and shown when there are todos -->
			<footer class="footer" v-show="todoList.length">
				<!-- This should be `0 items left` by default -->
				<span class="todo-count"><strong>{{ count }}</strong> item{{ count>1?'s':'' }} left</span>
				<!-- Remove this if you don't implement routing -->
				<ul class="filters">
					<li>
						<a class="{'selected':filterTodoList=='all'}" href="#/">All</a>
					</li>
					<li>
						<a class="{'selected':filterTodoList=='active'}" href="#/active">Active</a>
					</li>
					<li>
						<a class="{'selected':filterTodoList=='completed'}" href="#/completed">Completed</a>
					</li>
				</ul>
				<!-- Hidden if no completed items are left ↓ -->
				<button class="clear-completed" @click="removeCompleted" v-show="count !=todoList.length">Clear completed</button>
			</footer>
		</section>
		<footer class="info">
			<p>Double-click to edit a todo</p>
			<!-- Remove the below line ↓ -->
			<p>Template by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
			<!-- Change this out with your name and url ↓ -->
			<p>Created by <a href="http://todomvc.com">you</a></p>
			<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
		</footer>
</template>

<script setup lang="ts">
    import {reactive, toRefs, computed,watch} from 'vue'
    interface TodoItem{
        id: number;
        content: string;
        completed: boolean
    }
    interface Data{
        todoList:Array<TodoItem>,
        content:string,
		current:TodoItem | null,
		filterStatus:string
    }
	//存储数据对应的key
    const STORAGE_KEY = 'todo_data'
    //本地存储数据对象
	const itemStorage = {
	//读数据
        fetch(){
            return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
        },
	//持久化数据
        save(items){
            localStorage.setItem(STORAGE_KEY,JSON.stringify(items))
        }
   }

    let data:Data = reactive({
        todoList:itemStorage.fetch(),
        content:'',
		current:null,
		filterStatus:'all'
    })
	//获取数据
    let {todoList,content,current,filterStatus} ={...toRefs(data)}
	//添加任务项
    // toRefs(data)
    function addData(){
        if(content.value){
            todoList.value.push({
                id:todoList.value.length+1,
                content:content.value,
                completed:false
            })
            content.value = ''
        }
    }
	// 统计未完成任务项
	const count = computed(()=>todoList.value.filter(item=>!item.completed).length)
	//全选/取消全选
	const toggleAll = computed({
        get(){   
            return count.value == 0
        },
        set(state){
            data.todoList.forEach(item=>item.completed=state)
        }
    })
	//删除任务项
	function removeItem(index:number){
       data.todoList.splice(index,1);
    }
	//删除已完成任务项
    function removeCompleted(){
       const t = todoList.value.filter(item => !item.completed)
       data.todoList.splice(0,todoList.value.length)
       data.todoList.push(...t)
	}
	//双击修改任务项
	function editItem(item:TodoItem){
		data.current = item
	}
	//取消编辑
	function cancelEdit(){
        data.current = null
	}
	//编辑数据
	function finishEdit(index:number,item:TodoItem,event:any){
        //Esc取消编辑也会自动触发blur事件，直接返回
        if(!data.current) return 
        //如果输入框没有内容，则执行移除操作
        const con = event.target.value.trim()
        if(!con){
            removeItem(index)
            return
        }
        //编辑操作
        item.content = con
        //编辑完成，当前编辑项设置为null,取消.editing样式
        data.current = null
    }
	//监听地址栏hash值的变化
	window.onhashchange = function(){
        let hash = window.location.hash.substring(2) || 'all'//截取#/后面的值，如果没有，则默认为all号后面的值

        filterStatus.value = hash
   }
   const filterTodoList = computed(() => {
    switch(filterStatus.value){
        case 'active':
            return data.todoList.filter(item => !item.completed)
            break
        case 'completed':
            return data.todoList.filter(item => item.completed)
            break
        default:
            return data.todoList
            break
    }
   })

//监听todoList有改变，就保存最新的数据
	watch(todoList.value,()=>{
        console.log('数据变化了')
        itemStorage.save(todoList.value)
    })




</script>
